package com.xiebishe.mylibrary.base;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.Settings;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.view.OnApplyWindowInsetsListener;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.trello.rxlifecycle3.components.support.RxAppCompatActivity;
import com.xiebishe.mylibrary.common.WindowUtils;
import com.xiebishe.mylibrary.common.pageStatus.DefaultStatusHandler;
import com.xiebishe.mylibrary.common.pageStatus.StatusHandler;
import com.xiebishe.mylibrary.common.permission.PermissionHandler;

import com.xiebishe.mylibrary.common.permission.PermissionFail;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.List;

import io.reactivex.functions.Consumer;
import kotlin.coroutines.CoroutineContext;
import kotlinx.coroutines.CoroutineScope;
import kotlinx.coroutines.Dispatchers;
import kotlinx.coroutines.Job;
import kotlinx.coroutines.SupervisorKt;


/**
 * @class BaseActivity
 * @describe Activity的基类
 * 1.包括显示不同状态的界面
 * 2.ButterKnife的绑定和解绑
 * 3.EventBus的注册和注销
 * 4.presenter的注销(伴随model的注销)
 */
public abstract class BaseActivity extends RxAppCompatActivity implements  OnApplyWindowInsetsListener, CoroutineScope {

    protected Context mContext = null;//context
    private StatusHandler statusHandler;
    private PermissionHandler permissionHandler;
    private boolean isResumed;
    private long dispatchTouchAfterThis = 0;
    private Job job;
    private CoroutineContext coroutineContext;
    public int topInset;
    public int bottomInset;
    public int leftInset;
    public int rightInset;
    public boolean isNoStatusBarColor(){
        return true;
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isNoStatusBarColor()){
            WindowUtils.setStatusBarColor(getWindow(), 0xffffffff);
            WindowUtils.setNavigationBarColor(getWindow(), 0xffffffff);
            WindowUtils.setLightStatus(getWindow());
            WindowUtils.setLightNavigation(getWindow());
        }
        job = SupervisorKt.SupervisorJob(null);
        coroutineContext = Dispatchers.getMain().plus(job);
        ViewCompat.setOnApplyWindowInsetsListener(getWindow().getDecorView(), this);
        permissionHandler = new PermissionHandler(this);

        init(savedInstanceState);
    }

    @NotNull
    @Override
    public CoroutineContext getCoroutineContext() {
        return coroutineContext;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        permissionHandler.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void requestPermission(Consumer<List<PermissionFail>> consumer, String... permissions) {
        permissionHandler.requestPermissionInJava(consumer, permissions);
    }

    public boolean hasPermission(String... permissions) {
        return permissionHandler.hasPermission(permissions);
    }

    public interface OnCustomPermissionAccept {
        void onAccept();

    }

    protected void init(Bundle savedInstanceState) {
        mContext = this;
        if (getContentViewID() != 0) {
            setContentView(getContentViewID());
        }
        statusHandler = createStatusHandler();
        initDatas(savedInstanceState);
        if (useEventBus()) {//如果要使用eventbus请将此方法返回true
            EventBus.getDefault().register(this);//注册eventbus
        }
        doCustomThingsBetweenDataAndView(savedInstanceState);
        initViews(savedInstanceState);
        doCustomThingsAfterView();
    }

    protected void reloadData() {
    }

    final protected void setErrorView(View view) {
        statusHandler.setErrorView(view);
    }

    /**
     * 自定义Activity时，有时可在次内部加上定制需求
     * <p>
     * contentview设置完，initDatas执行后，initView执行前
     */
    protected void doCustomThingsBetweenDataAndView(Bundle savedInstanceState) {
    }

    protected void doCustomThingsAfterView() {

    }



    @Override
    protected void onResume() {
        super.onResume();
        isResumed = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResumed = false;
    }

    protected void pageShow() {

    }

    protected void pageShowError() {

    }

    protected void pageShowEmpty() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        job.cancel(null);
        if (useEventBus())//如果要使用eventbus请将此方法返回true
            EventBus.getDefault().unregister(this);//解除注册eventbus

    }

    /**
     * --------------------------------------子类  必须   实现的部分，包括:获得contentView的id,初始化view-----------------------
     */


    /**
     * 获得contentview的id
     */
    public abstract int getContentViewID();


    /**
     * 初始化data
     */
    public abstract void initDatas(@Nullable Bundle savedInstanceState);

    /**
     * 初始化view
     */
    public abstract void initViews(@Nullable Bundle savedInstanceState);




    /**
     * --------------------------------------子类  选择   实现的部分，包括:是否需要EventBus-----------------------
     */


    /**
     * 是否使用eventBus,默认为不使用(false)，
     *
     * @return
     */
    public boolean useEventBus() {
        return false;
    }

    protected void removeAllFragments() {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        FragmentTransaction bt = getSupportFragmentManager().beginTransaction();
        for (Fragment fragment : fragments) {
            bt.remove(fragment);
        }
        bt.commitNowAllowingStateLoss();
    }


    /**
     * --------------------------------------口-----------------------
     */
    public final void showLoading() {
        statusHandler.loading();
        onShowLoading();
    }

    public final void showError() {
        statusHandler.error();
        onShowError();
    }

    public final void showEmpty() {
        statusHandler.empty();
        onShowEmpty();
    }

    public final void showContent() {
        statusHandler.showContent();
        onShowContent();
    }

    public void onShowContent() {

    }

    public void onShowEmpty() {

    }

    public void onShowError() {

    }

    public void onShowLoading() {

    }

    /**
     * --------------------------------------展示不同状态界面的方法（内容界面,正在加载界面，空画面，出错画面）-----------------------
     */
    public void startToSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", this.getPackageName(), null);
        intent.setData(uri);
        startActivity(intent);
    }

    @Override
    public final WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
        topInset = insets.getSystemWindowInsetTop();
        bottomInset = insets.getSystemWindowInsetBottom();
        leftInset = insets.getSystemWindowInsetLeft();
        rightInset = insets.getSystemWindowInsetRight();
        onInset();
        return ViewCompat.onApplyWindowInsets(v, insets);
    }

    protected void onInset() {
    }

    public boolean isActivityResumed() {
        return isResumed;
    }

    protected StatusHandler createStatusHandler() {
        FrameLayout content = findViewById(android.R.id.content);
        return new DefaultStatusHandler(content, v -> {
            reloadData();
        });
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
        dispatchTouchAfterThis = SystemClock.elapsedRealtime() + 1000;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        long nowTime = SystemClock.elapsedRealtime();
        if (nowTime >= dispatchTouchAfterThis || ev.getAction() != MotionEvent.ACTION_DOWN) {
            return super.dispatchTouchEvent(ev);
        } else {
            return true;
        }
    }



}
